﻿/*	
	stencil - action script 3 isometric game engine.

	http://code.google.com/p/stencilas3/
	
	Copyright (c) 2010 Max Zhuravkov, All Rights Reserved.

	Permission is hereby granted, free of charge, to any person obtaining a copy of
	this software and associated documentation files (the "Software"), to deal in
	the Software without restriction, including without limitation the rights to
	use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
	of the Software, and to permit persons to whom the Software is furnished to do
	so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.
*/
package stencil.core.engine 
{
	import flash.utils.Dictionary;
	import stencil.core.engine.Box;
	
	/**
	 * 
	 * @author Max Zhuravkov
	 */
	public class SceneObjectGrid{
		
		private var _objectPositions:Dictionary = new Dictionary();
		
		private var _grid:Dictionary = new Dictionary();
		
		private var _objects:Dictionary = new Dictionary();
		
		private var _callbacks:Array = [];
		
		private var _position:Position = new Position();
		
		//------------------------------------------------------------------------------------------------
		// Constructor
		//------------------------------------------------------------------------------------------------
	
		public function SceneObjectGrid() {
			
		}
		
		//------------------------------------------------------------------------------------------------
		// Public methods
		//------------------------------------------------------------------------------------------------
		
		/**
		 * 
		 * @param	callback
		 */
		public function addCallback(callback:Function):void {
			if(this._callbacks.indexOf(callback)== -1){
				this._callbacks.push(callback)
			}
		}
		
		/**
		 * 
		 * @param	callback
		 */
		public function removeCallback(callback:Function):void {
			var index:int = this._callbacks.indexOf(callback);
			if (index >= 0) {
				this._callbacks.splice(1, index);
			}
		}
		
		/**
		 * Adds object to grid or updates its position if this object is already within grid.
		 * @param	o	the object to be add.
		 */
		public function putOrUpdate(o:ISceneObject):void {
			var op:ObjectPosition = this._objectPositions[o.id];
			var p:Position = o.position;
			var nextFloor:Dictionary = this._grid[p.z];
			
			if (!op) {
				
				op = new ObjectPosition(o);
				
				this._objectPositions[o.id] = op;
				this._objects[o.id] = o;
				
				this.addTo(o, nextFloor);
			}else {
				
				if (op.areaChanged(o)) {
					var previousFloor:Dictionary = this._grid[p.z];
					
					this.removeFrom(o, op, previousFloor);
					this.addTo(o, nextFloor);
					
					op.setTo(o);
				}
			}
		}
		
		/**
		 * Removes the given object from grid.
		 * @param	o	the object to be removed.
		 */
		public function remove(o:ISceneObject):void {
			var op:ObjectPosition = this._objectPositions[o.id];
			if (!op) {
				return;
			}
			var floor:Dictionary = this._grid[op.z];
			this.removeFrom(o, op, floor);
			
			delete this._objects[o.id];
			delete this._objectPositions[o.id];
		}
		
		/**
		 * Returns the array of objects that occupy the given position.
		 * 
		 * @return
		 */
		public function getObjectsAt(p:Position, filter:Function):Array {
			var floor:Dictionary = this._grid[p.z];
			var pi:Number = p.y * 10000 + p.x;
			if (!floor) {
				return null;
			}
			var foundObjects:Array = floor[pi];
			if (!foundObjects) {
				return null;
			}
			var result:Array = null;
			
			if (filter != null) {
				result = [];
				
				for each(var oid:String in foundObjects) {
					var o:ISceneObject = this._objects[oid];
					if (filter.call(null, o)) {
						result.push(o);
					}
				}
				
			}else {
				result = new Array(foundObjects.length);
				var i:int = 0;
				
				
				
				for each(var id:String in foundObjects) {
					result[i ++] = this._objects[id];
				}
			}
			return result;
		}
		
		/**
		 * Clears grid.
		 */
		public function clear():void {
			this._grid =  new Dictionary();
			this._objectPositions = new Dictionary();
			this._objects = new Dictionary();
		}
		
		//------------------------------------------------------------------------------------------------
		// Private methods
		//------------------------------------------------------------------------------------------------
		
		private function removeFrom(o:ISceneObject, op:ObjectPosition, floor:Dictionary):void {
			var maxx:int = op.x + op.w;
			var maxy:int = op.y + op.h;
			var z:int = op.z;
			var id:String = o.id;
			
			if (!floor) {
				floor = new Dictionary();
				this._grid[z] = floor;
			}
			
			for (var i:int = op.x; i < maxx; i ++ ) {
				for (var j:int = op.y; j < maxy; j ++ ) {
					var pi:Number = j * 10000 + i;
					var objects:Array = floor[pi];
					if (!objects) {
						continue;
					}
					var index:int = objects.indexOf(id);
					if (index != -1 ) {
						objects.splice(index, 1);
						
						if (this._callbacks.length) {
							for each(var callback:Function in this._callbacks) {
								this._position.x = i;
								this._position.y = j;
								this._position.z = z;
								
								callback.call(null, this._position, o, false);
							}
						}
					}
				}
			}
		}
		
		private function addTo(o:ISceneObject, floor:Dictionary):void {
			
			var p:Position = o.position;
			var d:Box = o.dimensions;
			var maxx:int = p.x + (d ? d.dx : 1);
			var maxy:int = p.y + (d ? d.dy : 1);
			var z:int = p.z;
			
			if (!floor) {
				floor = new Dictionary();
				this._grid[z] = floor;
			}
			
			for (var i:int = p.x; i < maxx; i ++ ) {
				for (var j:int = p.y; j < maxy; j ++ ) {
					var pi:Number = j * 10000 + i;
					var objects:Array = floor[pi];
					if (!objects) {
						objects = [];
						floor[pi] = objects;
					}
					var index:int = objects.indexOf(o.id);
					if (index == -1 ) {
						objects.push(o.id)
						
						if (this._callbacks.length) {
							for each(var callback:Function in this._callbacks) {
								this._position.x = i;
								this._position.y = j;
								this._position.z = z;
								
								callback.call(null, this._position, o, true);
							}
						}
					}
				}
			}
		}
	}

}

import stencil.core.engine.ISceneObject;
import stencil.core.engine.Position;
import stencil.core.engine.Box;

internal class ObjectPosition {
	
	public var x:Number;
	
	public var y:Number;
	
	public var z:Number;
	
	public var w:Number;
	
	public var h:Number;
	
	//----------------------------------------------------------------
	// Constructor
	//----------------------------------------------------------------
	
	public function ObjectPosition(o:ISceneObject) {
		this.setTo(o);
	}
	
	//----------------------------------------------------------------
	// Public methods
	//----------------------------------------------------------------
	
	public function setTo(o:ISceneObject):void {
		var p:Position = o.position;
		var d:Box = o.dimensions;
		
		this.x = p.x;
		this.y = p.y;
		this.z = p.z;
		this.w = (d ? d.dx : 1);
		this.h = (d ? d.dy : 1);
	}
	
	public function areaChanged(o:ISceneObject):Boolean {
		return o.dimensions.dx == w && o.dimensions.dy == h && x == o.position.x && y == o.position.y && z == o.position.z;
	}
}